"""
P2任务集成示例 - 容错降级、安全加固、灰度发布

这个示例展示了P2优先级任务的所有模块如何协同工作：
- 熔断器、降级策略、兜底机制
- 双向认证、密钥轮换、速率限制
- Feature Flag、配置审计、版本回滚
"""

import asyncio
import logging
import time
from uuid import uuid4
from typing import Dict, Any

# 导入P2模块
from .circuit_breaker import CircuitBreaker, CircuitBreakerConfig, get_circuit_breaker_manager
from .degradation_manager import DegradationManager, DegradationConfig, DegradationLevel, DegradationRule, DegradationAction
from .fallback_manager import FallbackManager, FallbackConfig, FallbackStrategy, FallbackType, FallbackPriority
from .mtls_auth import MTLSManager, MTLSConfig, get_mtls_manager
from .key_rotation import KeyManager, KeyRotationConfig, KeyType, get_key_manager
from .feature_flag import FeatureFlagManager, FeatureFlagConfig, FeatureFlagType, FeatureFlagStatus, get_feature_flag_manager
from .config_audit import ConfigAuditManager, AuditConfig, ChangeType, get_config_audit_manager
from .version_rollback import VersionManager, RollbackConfig, VersionInfo, VersionStatus, get_version_manager

# 导入速率限制器
import sys
sys.path.append('/home/ubuntu/PhotoEnhanceAI-web/api-gateway')
from rate_limiter import RateLimiter, RateLimitConfig, RateLimitScope, get_rate_limiter

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


class P2IntegrationDemo:
    """P2集成演示类"""
    
    def __init__(self):
        # 初始化所有管理器
        self.circuit_breaker_manager = get_circuit_breaker_manager()
        self.degradation_manager = DegradationManager()
        self.fallback_manager = FallbackManager()
        self.mtls_manager = get_mtls_manager()
        self.key_manager = get_key_manager()
        self.feature_flag_manager = get_feature_flag_manager()
        self.config_audit_manager = get_config_audit_manager()
        self.version_manager = get_version_manager()
        self.rate_limiter = get_rate_limiter()
        
        self.logger = logging.getLogger(f"{__name__}.P2IntegrationDemo")
    
    async def setup_all_managers(self):
        """设置所有管理器"""
        self.logger.info("开始设置所有P2管理器...")
        
        # 1. 启动降级管理器
        await self.degradation_manager.start()
        
        # 2. 启动兜底管理器
        await self.fallback_manager.start()
        
        # 3. 启动密钥管理器
        await self.key_manager.start()
        
        # 4. 启动配置审计管理器
        await self.config_audit_manager.start()
        
        # 5. 启动版本管理器
        await self.version_manager.start()
        
        # 6. 初始化mTLS证书
        await self.mtls_manager.initialize_certificates()
        
        self.logger.info("所有P2管理器设置完成")
    
    async def demo_circuit_breaker_and_degradation(self):
        """演示熔断器和降级策略"""
        self.logger.info("=== 熔断器和降级策略演示 ===")
        
        # 注册服务
        await self.degradation_manager.register_service("gpu_processing_service")
        
        # 创建熔断器
        circuit_config = CircuitBreakerConfig(
            failure_threshold=3,
            failure_rate_threshold=0.5,
            recovery_timeout=30
        )
        
        circuit_breaker = await self.circuit_breaker_manager.get_circuit_breaker(
            "gpu_service_cb",
            config=circuit_config
        )
        
        # 添加降级规则
        degradation_rule = DegradationRule(
            name="high_error_rate",
            service_name="gpu_processing_service",
            condition="success_rate_low",
            target_level=DegradationLevel.MEDIUM
        )
        await self.degradation_manager.add_degradation_rule(degradation_rule)
        
        # 添加降级动作
        degradation_action = DegradationAction(
            name="reduce_capacity",
            service_name="gpu_processing_service",
            level=DegradationLevel.MEDIUM,
            action_type="reduce",
            parameters={"capacity_percentage": 50}
        )
        await self.degradation_manager.add_degradation_action(degradation_action)
        
        # 模拟服务调用
        async def failing_service():
            raise Exception("模拟服务失败")
        
        # 测试熔断器
        for i in range(5):
            try:
                await circuit_breaker.call(failing_service)
                self.logger.info(f"服务调用成功: {i+1}")
            except Exception as e:
                self.logger.warning(f"服务调用失败: {i+1}, 错误: {e}")
        
        # 获取熔断器状态
        stats = await circuit_breaker.get_stats()
        self.logger.info(f"熔断器状态: {stats.current_state.value}")
        
        # 获取降级状态
        degradation_status = await self.degradation_manager.get_degradation_status()
        self.logger.info(f"降级状态: {degradation_status}")
    
    async def demo_fallback_mechanisms(self):
        """演示兜底机制"""
        self.logger.info("=== 兜底机制演示 ===")
        
        # 注册兜底策略
        cache_strategy = FallbackStrategy(
            name="cache_fallback",
            service_name="gpu_processing_service",
            fallback_type=FallbackType.CACHE,
            priority=FallbackPriority.HIGH,
            trigger_conditions=["service_unavailable"],
            cache_ttl=300
        )
        await self.fallback_manager.register_fallback_strategy(cache_strategy)
        
        # 注册静态兜底策略
        static_strategy = FallbackStrategy(
            name="static_fallback",
            service_name="gpu_processing_service",
            fallback_type=FallbackType.STATIC,
            priority=FallbackPriority.MEDIUM,
            trigger_conditions=["service_unavailable"],
            metadata={"static_data": {"message": "服务暂时不可用，请稍后重试"}}
        )
        await self.fallback_manager.register_fallback_strategy(static_strategy)
        
        # 模拟主要服务
        async def primary_service():
            raise Exception("主要服务不可用")
        
        # 测试兜底机制
        result = await self.fallback_manager.execute_with_fallback(
            "gpu_processing_service",
            primary_service
        )
        
        self.logger.info(f"兜底结果: {result.success}, 数据: {result.data}")
        
        # 获取兜底状态
        fallback_status = await self.fallback_manager.get_fallback_status()
        self.logger.info(f"兜底状态: {fallback_status}")
    
    async def demo_security_features(self):
        """演示安全特性"""
        self.logger.info("=== 安全特性演示 ===")
        
        # 1. 密钥轮换演示
        # 生成RSA密钥
        rsa_key_id = await self.key_manager.generate_key(KeyType.RSA)
        await self.key_manager.activate_key(rsa_key_id)
        
        # 生成HMAC密钥
        hmac_key_id = await self.key_manager.generate_key(KeyType.HMAC)
        await self.key_manager.activate_key(hmac_key_id)
        
        # 获取活跃密钥
        rsa_key = await self.key_manager.get_active_key(KeyType.RSA)
        hmac_key = await self.key_manager.get_active_key(KeyType.HMAC)
        
        self.logger.info(f"RSA密钥ID: {rsa_key_id}")
        self.logger.info(f"HMAC密钥ID: {hmac_key_id}")
        
        # 2. 速率限制演示
        # 检查速率限制
        rate_limit_info = await self.rate_limiter.check_rate_limit(
            scope=RateLimitScope.IP,
            identifier="192.168.1.100",
            endpoint="/api/gpu/process"
        )
        
        self.logger.info(f"速率限制: 允许={rate_limit_info.allowed}, 剩余={rate_limit_info.remaining}")
        
        # 3. mTLS证书状态
        cert_status = await self.mtls_manager.get_certificate_status()
        self.logger.info(f"证书状态: {len(cert_status['certificates'])} 个证书")
    
    async def demo_feature_flags(self):
        """演示Feature Flag"""
        self.logger.info("=== Feature Flag演示 ===")
        
        # 创建功能开关
        feature_config = FeatureFlagConfig(
            name="new_gpu_algorithm",
            description="新的GPU处理算法",
            flag_type=FeatureFlagType.BOOLEAN,
            status=FeatureFlagStatus.ROLLOUT,
            rollout_percentage=50.0,
            targeting_rules=[
                {
                    "name": "beta_users",
                    "type": "user_group",
                    "config": {"groups": ["beta_testers"]}
                }
            ]
        )
        
        await self.feature_flag_manager.create_flag(feature_config)
        
        # 评估功能开关
        context = {"user_id": "user123", "user_group": "beta_testers"}
        evaluation = await self.feature_flag_manager.evaluate_flag("new_gpu_algorithm", context)
        
        self.logger.info(f"功能开关评估: {evaluation.value}, 原因: {evaluation.reason}")
        
        # 获取分析数据
        analytics = await self.feature_flag_manager.get_analytics("new_gpu_algorithm")
        self.logger.info(f"功能开关分析: {analytics}")
    
    async def demo_config_audit(self):
        """演示配置审计"""
        self.logger.info("=== 配置审计演示 ===")
        
        # 记录配置变更
        change_id = await self.config_audit_manager.record_change(
            change_type=ChangeType.UPDATE,
            config_name="gpu_processing_config",
            config_type="application",
            old_value={"batch_size": 10, "timeout": 30},
            new_value={"batch_size": 20, "timeout": 60},
            description="增加批处理大小和超时时间",
            reason="性能优化",
            user_id="admin",
            user_name="Administrator"
        )
        
        self.logger.info(f"配置变更记录: {change_id}")
        
        # 审批变更
        await self.config_audit_manager.approve_change(
            change_id=change_id,
            approver_id="manager",
            approver_name="Manager",
            approved=True,
            notes="配置变更已审核通过"
        )
        
        # 应用变更
        await self.config_audit_manager.apply_change(change_id)
        
        # 获取变更历史
        changes = await self.config_audit_manager.list_changes(limit=5)
        self.logger.info(f"最近变更: {len(changes)} 个")
        
        # 生成审计报告
        report = await self.config_audit_manager.generate_audit_report()
        self.logger.info(f"审计报告: 总变更数={report['statistics']['total_changes']}")
    
    async def demo_version_rollback(self):
        """演示版本回滚"""
        self.logger.info("=== 版本回滚演示 ===")
        
        # 注册版本
        version1_id = "v1.0.0"
        await self.version_manager.register_version(
            version_id=version1_id,
            version_name="Initial Version",
            description="初始稳定版本",
            git_commit="abc123",
            build_number="1"
        )
        
        version2_id = "v1.1.0"
        await self.version_manager.register_version(
            version_id=version2_id,
            version_name="Feature Update",
            description="功能更新版本",
            git_commit="def456",
            build_number="2"
        )
        
        # 标记v1.0.0为稳定版本
        await self.version_manager.mark_version_as_stable(version1_id)
        
        # 部署v1.1.0
        await self.version_manager.deploy_version(version2_id)
        
        # 模拟问题，回滚到稳定版本
        rollback_id = await self.version_manager.rollback_to_version(
            target_version_id=version1_id,
            reason="新版本出现性能问题",
            initiated_by="admin"
        )
        
        self.logger.info(f"回滚执行: {rollback_id}")
        
        # 获取当前版本
        current_version = await self.version_manager.get_current_version()
        self.logger.info(f"当前版本: {current_version.version_name if current_version else 'None'}")
        
        # 获取回滚历史
        rollback_history = await self.version_manager.get_rollback_history(limit=5)
        self.logger.info(f"回滚历史: {len(rollback_history)} 个记录")
    
    async def demo_integrated_workflow(self):
        """演示集成工作流"""
        self.logger.info("=== 集成工作流演示 ==="")
        
        # 模拟一个完整的请求处理流程
        request_id = str(uuid4())
        user_id = "user123"
        ip_address = "192.168.1.100"
        
        self.logger.info(f"处理请求: {request_id}")
        
        # 1. 速率限制检查
        rate_limit_info = await self.rate_limiter.check_rate_limit(
            scope=RateLimitScope.USER,
            identifier=user_id,
            endpoint="/api/gpu/process"
        )
        
        if not rate_limit_info.allowed:
            self.logger.warning("请求被速率限制")
            return
        
        # 2. Feature Flag检查
        context = {"user_id": user_id, "ip_address": ip_address}
        feature_evaluation = await self.feature_flag_manager.evaluate_flag("new_gpu_algorithm", context)
        
        if feature_evaluation.value:
            self.logger.info("使用新算法处理")
        else:
            self.logger.info("使用传统算法处理")
        
        # 3. 熔断器保护的服务调用
        circuit_breaker = await self.circuit_breaker_manager.get_circuit_breaker("gpu_service_cb")
        
        async def gpu_processing_service():
            # 模拟GPU处理
            await asyncio.sleep(0.1)
            return {"result": "processing_completed", "request_id": request_id}
        
        try:
            result = await circuit_breaker.call(gpu_processing_service)
            self.logger.info(f"GPU处理完成: {result}")
        except Exception as e:
            self.logger.warning(f"GPU处理失败，触发兜底: {e}")
            
            # 4. 兜底机制
            fallback_result = await self.fallback_manager.execute_with_fallback(
                "gpu_processing_service",
                gpu_processing_service
            )
            
            if fallback_result.success:
                self.logger.info(f"兜底处理成功: {fallback_result.data}")
            else:
                self.logger.error(f"兜底处理失败: {fallback_result.error_message}")
        
        # 5. 记录配置变更（如果需要）
        if feature_evaluation.value:
            await self.config_audit_manager.record_change(
                change_type=ChangeType.UPDATE,
                config_name="algorithm_selection",
                config_type="runtime",
                old_value="traditional",
                new_value="new_algorithm",
                description="算法选择变更",
                reason="Feature Flag触发",
                user_id=user_id
            )
    
    async def cleanup(self):
        """清理资源"""
        self.logger.info("清理资源...")
        
        await self.degradation_manager.stop()
        await self.fallback_manager.stop()
        await self.key_manager.stop()
        await self.config_audit_manager.stop()
        await self.version_manager.stop()
        await self.mtls_manager.close_all_clients()
        
        self.logger.info("资源清理完成")


async def main():
    """主函数"""
    logger.info("开始P2任务集成演示...")
    
    demo = P2IntegrationDemo()
    
    try:
        # 设置所有管理器
        await demo.setup_all_managers()
        
        # 演示各个功能模块
        await demo.demo_circuit_breaker_and_degradation()
        await demo.demo_fallback_mechanisms()
        await demo.demo_security_features()
        await demo.demo_feature_flags()
        await demo.demo_config_audit()
        await demo.demo_version_rollback()
        
        # 演示集成工作流
        await demo.demo_integrated_workflow()
        
        logger.info("P2任务集成演示完成")
        
    except Exception as e:
        logger.error(f"演示过程中出现错误: {e}")
    
    finally:
        # 清理资源
        await demo.cleanup()


if __name__ == "__main__":
    asyncio.run(main())
